package com.kongxr.opengltest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.widget.Toast;

import com.tencent.liteav.basic.d.m;
import com.tencent.liteav.renderer.TXCGLSurfaceView;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TXLivePushConfig mLivePushConfig;
    private TXLivePusher mLivePusher;
    private boolean mIsPreView;
    private TXCloudVideoView txCloudVideoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkPublishPermission();
        setContentView(R.layout.activity_main);
        initVeiw();
        initPusher();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (checkPublishPermission()) {
            push();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (txCloudVideoView != null) {
            txCloudVideoView.onResume();
        }
        Log.d("MainActivity", "TxMainActivity--onResume");
//        if (!mLivePusher.isPushing()) mLivePusher.resumePusher();
    }

    private void initVeiw() {
        txCloudVideoView = findViewById(R.id.txv_pre);
    }
    private void initPusher() {
        mLivePusher = new TXLivePusher(this);
        mLivePushConfig = new TXLivePushConfig();
        mLivePushConfig.setVideoFPS(12);
        mLivePushConfig.setVideoEncodeGop(5);
        mLivePusher.setConfig(mLivePushConfig);
//        mLivePusher.setVideoProcessListener(this);
    }


    private void push() {
        if (mIsPreView) return;
//        int[] beautyData = new int[]{-1,-1,-1,50,30,40,50,70,10,50,40,20,80,40,60,50};
//        BeautyDataModel.getInstance().setBeautyDataMap(beautyData);
        //String rtmpUrl = "https://room.qcloud.com/weapp/live_room/add_pusher?userID=user_4debca9c_515e&token=5bacc8b47ebca9651466c36a195f4c4f";
        String rtmpUrl = "rtmp://3891.livepush.myqcloud.com/live/3891_user_b04a6109_1af7?bizid=3891&txSecret=611e618e88dcfd79711961cb66442e54&txTime=5CE28D09";//mRtmp.getText().toString();
//        int i = mLivePusher.startPusher(rtmpUrl);
//        Log.d("mLivePusherResult==" , i+"");
//        mLivePushConfig.setVideoBitrate(1200);
//        mLivePushConfig.setAutoAdjustBitrate(false);
//        mLivePushConfig.setVideoFPS(20);
        txCloudVideoView.setVisibility(View.VISIBLE);
//        mLivePusher.setPushListener(this);
        mLivePushConfig.setVideoResolution(TXLiveConstants.VIDEO_RESOLUTION_TYPE_540_960);
//        mLivePushConfig.setVideoResolution(TXLiveConstants.VIDEO_RESOLUTION_TYPE_360_640);
        mLivePushConfig.setHomeOrientation(TXLiveConstants.VIDEO_ANGLE_HOME_DOWN);
//        int[] beautyDefaultDatas = BeautyDataModel.getInstance().getDefaultAllBeautyDatas();
//        mLivePusher.setBeautyFilter(TXLiveConstants.BEAUTY_STYLE_SMOOTH, beautyDefaultDatas[0], beautyDefaultDatas[1], beautyDefaultDatas[2]);
        mLivePusher.setMirror(true);
        // 设置自定义视频处理回调，在主播预览及编码前回调出来，用户可以用来做自定义美颜或者增加视频特效
        mLivePusher.setConfig(mLivePushConfig);
//        setPushScene(TXLiveConstants.VIDEO_QUALITY_HIGH_DEFINITION, false);
//        TXCloudVideoView txCloudVideoView = new TXCloudVideoView(getApplicationContext());
//        txCloudVideoView.removeVideoView();
//        txCloudVideoView.addVideoView(mCaptureView);
        mLivePusher.startCameraPreview(txCloudVideoView);
//        setTxFilter();
//        mLivePusher.startPusher()
//        mIsPushing = true;
        mIsPreView =true;
        TXCGLSurfaceView glSurfaceView = txCloudVideoView.getGLSurfaceView();
        SurfaceTexture surfaceTexture = glSurfaceView.getSurfaceTexture();
        //surfaceTexture == null;
//        surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
//            @Override
//            public void onFrameAvailable(SurfaceTexture surfaceTexture) {
//                Log.d("MainActivity","onFrameAvailable");
//            }
//        });
        //glSurfaceView内部已有，重新设置导致黑屏
//        glSurfaceView.setSurfaceTextureListener(new m() {
//            @Override
//            public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture) {
//
//                Log.d("MainActivity","onSurfaceTextureAvailable");
//            }
//
//            @Override
//            public int onTextureProcess(int i, float[] floats) {
//                Log.d("MainActivity","onTextureProcess--i= " + i);
//                return i;
//            }
//
//            @Override
//            public void onBufferProcess(byte[] bytes, float[] floats) {
//                Log.d("MainActivity","onSurfaceTextureAvailable");
//            }
//
//            @Override
//            public void onSurfaceTextureDestroy(SurfaceTexture surfaceTexture) {
//                Log.d("MainActivity","onSurfaceTextureDestroy");
//            }
//        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPush();
    }

    private void stopPush() {
//        mLivePusher.stopBGM();
        mLivePusher.stopCameraPreview(true);
        mLivePusher.setPushListener(null);
//        mLivePusher.stopPusher();
        txCloudVideoView.setVisibility(View.GONE);
//        mPusherView.setVisibility(View.GONE);
//        mLivePushConfig.setPauseImg(null);
        mIsPreView = false;
    }


    private boolean checkPublishPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
//            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)) {
//                permissions.add(Manifest.permission.READ_PHONE_STATE);
//            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this,
                        permissions.toArray(new String[0]),
                        100);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean ret = true;
        if (grantResults.length > 0) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    ret = false;
                    break;
                }
            }
        }
        if (ret) {
            push();
        } else {
            Toast.makeText(this, "请重新启动，并开启权限", Toast.LENGTH_SHORT).show();
        }
    }
}
